package com.deepglint.processfunction;

import com.deepglint.beans.SensorReading;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @author mj
 * @version 1.0
 * @date 2021-11-23 0:10
 */
public class ProcessTest_KeyedProcessFunction {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env.getConfig().setAutoWatermarkInterval(200);// 设置周期性的waterMark的周期时间

        DataStream<String> streamSource = env.socketTextStream("192.168.150.128", 7777);

        DataStream<SensorReading> dataStream = streamSource.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], split[1], new Long(split[2]), new Double(split[3]));
        });

        SingleOutputStreamOperator<Integer> mapStream = dataStream.
                keyBy("id").
                process(new MyKeyedProcessFunction());

        mapStream.print();

        env.execute();
    }

    // 自定义的处理函数
    static class MyKeyedProcessFunction extends KeyedProcessFunction<Tuple, SensorReading, Integer> {

        private ValueState<Long> tsValueState;

        @Override
        public void open(Configuration parameters) throws Exception {
            tsValueState = getRuntimeContext().getState(new ValueStateDescriptor<Long>("my_value", Long.class));
        }

        @Override
        public void processElement(SensorReading value, KeyedProcessFunction<Tuple, SensorReading, Integer>.Context ctx, Collector<Integer> out) throws Exception {
            out.collect(value.getId().length());

            // 上下文环境
            ctx.timestamp();//当前时间
            ctx.getCurrentKey();// 当前key

//            ctx.output(); // 侧输出流
            ctx.timerService().currentProcessingTime();
            ctx.timerService().currentWatermark();
            ctx.timerService().registerProcessingTimeTimer(ctx.timerService().currentProcessingTime() + 10000L);// 再什么时间点触发，绝对时间(从1970年开始)
            tsValueState.update(ctx.timerService().currentProcessingTime() + 1000L);
//            ctx.timerService().registerEventTimeTimer((value.getTimestamp() + 1) * 1000L); // 延迟1秒开始执行
//            ctx.timerService().deleteProcessingTimeTimer(1000L); // 删除定时器
        }

        // 定时器触发时的操作
        @Override
        public void onTimer(long timestamp, KeyedProcessFunction<Tuple, SensorReading, Integer>.OnTimerContext ctx, Collector<Integer> out) throws Exception {
            System.out.println(timestamp + " 定时器触发");
            ctx.getCurrentKey();
            ctx.timeDomain();
//            ctx.output();
        }

        @Override
        public void close() throws Exception {
            tsValueState.clear();
        }
    }
}
